package org.jeecg.tender.taskJob;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.util.DateUtils;
import org.jeecg.readExcel.entity.TenderInformationKeywordManagementRelEntity;
import org.jeecg.readExcel.service.TenderInformationKeywordManagementRelService;
import org.jeecg.tender.config.WebDriverConfig;
import org.jeecg.tender.information.entity.TenderInformation;
import org.jeecg.tender.information.service.ITenderInformationService;
import org.jeecg.tender.keyword.entity.TenderSecurityKeywordManagement;
import org.jeecg.tender.keyword.service.ITenderSecurityKeywordManagementService;
import org.jeecg.tender.project.dto.req.SendProjectNoticeReqDto;
import org.jeecg.tender.project.dto.util.SendProjectNoticeUtil;
import org.jeecg.tender.project.service.ITenderProjectNoticeService;
import org.jeecg.tender.website.entity.TenderWebsiteManagement;
import org.jeecg.tender.website.service.ITenderWebsiteManagementService;
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.NoSuchElementException;

@Slf4j
public class QianlimaTaskJob implements Job {

    @Resource
    private ITenderInformationService tenderInformationService;

    @Resource
    private TenderInformationKeywordManagementRelService tenderInformationKeywordManagementRelService;

    @Resource
    private ITenderSecurityKeywordManagementService tenderSecurityKeywordManagementService;

    @Resource
    private ITenderWebsiteManagementService websiteManagementService;

    @Resource
    private WebDriverConfig webDriverConfig;

    @Resource
    private ITenderProjectNoticeService tenderProjectNoticeService;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        // 启动 Firefox 浏览器
        WebDriver driver = webDriverConfig.driver();
        List<SendProjectNoticeReqDto> noticeInfoList = new ArrayList<>();
        try {
            //更新招标网站爬取状态
            websiteManagementService.lambdaUpdate().eq(TenderWebsiteManagement::getWebsiteName,"千里马招标网")
                    .set(TenderWebsiteManagement::getCrawlStatus, 1).update();
            // 获取今天的日期
            LocalDate today = LocalDate.now();
            // 定义日期格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            // 格式化日期为字符串
            String todayString = today.format(formatter);

            List<TenderSecurityKeywordManagement> list =  tenderSecurityKeywordManagementService.lambdaQuery().list();
            for (int i = 1; i <= list.size(); i++) {
                TenderSecurityKeywordManagement tenderSecurityKeywordManagement = list.get(i-1);
                String keywordName = tenderSecurityKeywordManagement.getKeywordName();
                String baseUrl = "https://search.vip.qianlima.com/index.html#?keywords="+keywordName+"&timeType=4&beginTime="+todayString+"&endTime="+todayString+"&filtermode=2&sortType=1&keywordsFrom=0&allType=0&isSearchWord=1&tab_index=0"; // 基础 URL

                // 处理弹框（如果有）
                if(i==1){
                    //第一次进来才处理弹框和登录
                    closeModalIfPresent(driver,baseUrl);

                    //第一次进来才处理登录
                    try {
                        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(1));
                        WebElement timeoutPopup = wait.until(ExpectedConditions.presenceOfElementLocated(
                                By.xpath("//div[contains(@class, 'layui-layer-content') and contains(text(), '登录状态超时')]")
                        ));

                        if (timeoutPopup.isDisplayed()) {
                            log.info("检测到'登录状态超时'弹窗，关闭浏览器...");
                            driver.quit();  // 关闭浏览器
                            return;
                        }
                    } catch (TimeoutException e) {
                        log.info("未检测到'登录状态超时'弹窗，继续执行...");
                    } catch (Exception e) {
                        log.info("检查弹窗时发生异常：" + e.getMessage());
                    }
                }
                try {
                    WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(3));
                    WebElement popup = wait.until(ExpectedConditions.presenceOfElementLocated(
                            By.xpath("//div[contains(@class, 'layui-layer-content') and contains(text(), '精准搜索无结果')]")
                    ));

                    if (popup.isDisplayed()) {
                        log.info("检测到'精准搜索无结果'弹窗，跳过当前逻辑...");
                        Thread.sleep(3000); // 稍作等待
                        continue;  // 直接跳过本次操作
                    }
                } catch (TimeoutException e) {
                    log.info("未检测到弹窗，继续执行...");
                }

                log.info("匹配关键字::::::::::::::::::::：{}",keywordName);
                log.info("请求地址: {}", baseUrl);
                driver.get("about:blank"); // 先清空页面，确保 get 生效
                Thread.sleep(1000); // 稍作等待
                driver.get(baseUrl);

                try {
                    WebElement noDataDiv = null;
                    try {
                        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(3));
                        noDataDiv = wait.until(ExpectedConditions.presenceOfElementLocated(By.id("searchNotData")));
                    } catch (TimeoutException e) {
                        // 没有出现该元素，说明没有“未找到数据”的提示
                        log.info("未检测到 '未找到数据' 提示，继续执行...");
                    }

                    if (noDataDiv != null && noDataDiv.isDisplayed()) {
                        log.info("检测到 '未找到数据' 提示，跳过当前逻辑...");
                        continue;
                    }
                } catch (NoSuchElementException e) {
                    log.info("页面中未检测到'未找到数据'提示，继续执行...");
                }

                while (true) { // 无限循环，直到没有 "下一页"
                    try {
                        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(3));
                        WebElement captchaIframe = wait.until(ExpectedConditions.presenceOfElementLocated(
                                By.id("iframe_captcha")  // 定位 iframe
                        ));

                        if (captchaIframe.isDisplayed()) {
                            log.info("检测到验证码 iframe，立即关闭浏览器...");
                            driver.quit();  // 关闭浏览器
                            return;
                        }
                    } catch (TimeoutException e) {
                        log.info("未检测到验证码 iframe，继续执行...");
                    } catch (Exception e) {
                        log.info("检查验证码时发生异常：" + e.getMessage());
                    }

                    WebDriverWait wait2 = new WebDriverWait(driver, Duration.ofSeconds(10));
                    wait2.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(".con-title")));

                    // **重新获取 bidLinks**
                    List<WebElement> bidLinks = driver.findElements(By.cssSelector(".con-title"));
                    log.info("当前页面公告数量: {}", bidLinks.size());

                    for (int j = 0; j < bidLinks.size(); j++) {
                        WebElement link = bidLinks.get(j);
                        String title = link.getAttribute("title");
                        String detailUrl = link.getAttribute("data-url");
                        log.info("请求详情地址: {}", detailUrl);
                        log.info("第: {}条", j + 1);

                        Long count = tenderInformationService.lambdaQuery().eq(TenderInformation::getTenderTitle, title).count();
                        if (count > 0) {
                            log.info("该招标信息已存在，跳过当前公告。标题={}",title);
                            continue; // 跳过当前循环，继续下一次循环
                        }

                        if (detailUrl != null && !detailUrl.isEmpty()) {
                            TenderInformation tenderInformation = new TenderInformation();
                            log.info("Navigating to tender details page: " + detailUrl);
                            // 执行 JavaScript 在新标签页打开链接
                            ((JavascriptExecutor) driver).executeScript("window.open(arguments[0]);", detailUrl);

                            // 切换到新打开的标签页
                            ArrayList<String> tabs = new ArrayList<>(driver.getWindowHandles());
                            driver.switchTo().window(tabs.get(1));

                            // 等待页面加载
                            Thread.sleep(1000); // Adjust waiting time based on page load speed
                            try {
                                WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(3));
                                WebElement captchaIframe = wait.until(ExpectedConditions.presenceOfElementLocated(
                                        By.id("iframe_captcha")  // 定位 iframe
                                ));

                                if (captchaIframe.isDisplayed()) {
                                    log.info("检测到验证码 iframe，立即关闭浏览器...");
                                    driver.quit();  // 关闭浏览器
                                    return;
                                }
                            } catch (TimeoutException e) {
                                log.info("未检测到验证码 iframe，继续执行...");
                            } catch (Exception e) {
                                log.info("检查验证码时发生异常：" + e.getMessage());
                            }
                            try {
                                WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30));
                                wait.until(ExpectedConditions.presenceOfElementLocated(By.id("detailInfoContainer")));
                            } catch (org.openqa.selenium.TimeoutException e) {
                                // 超时后的处理代码，可以继续执行后续逻辑
                                log.warn("元素未在指定时间内加载，继续执行其他操作...");
                                // 关闭当前标签页
                                driver.close();
                                // 切换回原来的列表页
                                driver.switchTo().window(tabs.get(0));
                                Thread.sleep(2000); // 等待页面加载
                                continue;
                            }

                            // 获取详情内容
                            List<WebElement> detailContainers = driver.findElements(By.id("detailInfoContainer"));
                            if (detailContainers.isEmpty()) {
                                // 关闭当前标签页
                                driver.close();

                                // 切换回原来的列表页
                                driver.switchTo().window(tabs.get(0));
                                Thread.sleep(2000); // 等待页面加载
                                continue;
                            } else {
                                WebElement detailContainer = detailContainers.get(0);
                                if (detailContainer != null) {
                                    String detailContent = detailContainer.getText(); // Extract the content
                                    log.info("Detail Content: " + detailContent);
                                    if (StringUtils.isNotBlank(detailContent)) {
                                        tenderInformation.setTenderDesc(detailContent);
                                    }
                                }
                            }

                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                            String format = sdf.format(new Date());

                            extractFields(title, format, tenderInformation, "千里马招标网");
                            tenderInformationService.save(tenderInformation);
                            TenderInformationKeywordManagementRelEntity relEntity = new TenderInformationKeywordManagementRelEntity();
                            relEntity.setInformation_id(String.valueOf(tenderInformation.getId()));
                            relEntity.setSecurity_keyword_management_id(String.valueOf(tenderSecurityKeywordManagement.getId()));
                            relEntity.setCreate_by("system");
                            relEntity.setCreate_time(new Date());
                            tenderInformationKeywordManagementRelService.save(relEntity);
                            SendProjectNoticeReqDto sendProjectNoticeReqDto = SendProjectNoticeUtil.buildSendProjectNoticeReqDto(tenderSecurityKeywordManagement.getId(), tenderInformation);
                            sendProjectNoticeReqDto.setAddress(detailUrl);
                            sendProjectNoticeReqDto.setKeywordName(tenderSecurityKeywordManagement.getKeywordName());
                            noticeInfoList.add(sendProjectNoticeReqDto);
                            // 关闭当前标签页
                            driver.close();

                            // 切换回原来的列表页
                            driver.switchTo().window(tabs.get(0));
                            Thread.sleep(2000); // 等待页面加载
                        } else {
                            log.info("No valid link found, skipping.");
                        }
                    }

                    // **尝试点击下一页**
                    try {
                        // 获取页面上的 "下一页" 按钮
                        WebElement nextPageButton = driver.findElement(By.cssSelector("div.next.fr"));
                        String nextPageClass = nextPageButton.getAttribute("class");

                        // 如果 "下一页" 按钮不是 "disabled" 则点击下一页
                        if (!nextPageClass.contains("disabled")) {
                            log.info("点击下一页...");
                            String currentPageUrl = driver.getCurrentUrl(); // 获取当前页面的 URL
                            nextPageButton.click();

                            // 等待页面加载
                            Thread.sleep(2000); // 等待新页面加载

                            // 检查页面是否刷新（通过比较 URL 是否变化）
                            String newPageUrl = driver.getCurrentUrl();
                            if (currentPageUrl.equals(newPageUrl)) {
                                log.info("页面未更新，{}--已经是最后一页，结束爬取。",keywordName);
                                break; // 如果页面 URL 没有变化，说明是最后一页
                            }

                        } else {
                            log.info("没有更多页面，结束爬取。keywordName={}",keywordName);
                            break; // 没有下一页，退出循环
                        }
                    } catch (NoSuchElementException e) {
                        log.info("未找到下一页按钮，爬取完成。");
                        break; // 退出循环
                    }

                }

            }
            log.info("关闭浏览器...");
            driver.quit();
        } catch (Exception e) {
            // 关闭浏览器
            log.info("关闭浏览器...");
            driver.quit();
            e.printStackTrace();
        } finally {
                //更新招标网站爬取状态
                websiteManagementService.lambdaUpdate().eq(TenderWebsiteManagement::getWebsiteName,"千里马招标网")
                        .set(TenderWebsiteManagement::getCrawlStatus, 0).update();
            // 发送通知
            log.info("发送通知list:{}", JSON.toJSONString(noticeInfoList));
            tenderProjectNoticeService.sendTenderProjectNotice(noticeInfoList);

        }
    }

    // 检测并关闭弹框
    private void closeModalIfPresent(WebDriver driver, String baseUrl) {
        try {
            // 执行登录操作
            log.info("跳转到登录页面...");
            driver.get("https://vip.qianlima.com/login/");

            // 等待页面加载
            Thread.sleep(1000);

            // 填写账号
            WebElement usernameField = driver.findElement(By.name("username"));
            usernameField.sendKeys("anquan031094");

            // 填写密码
            WebElement passwordField = driver.findElement(By.name("password"));
            passwordField.sendKeys("Asp32T33");

            // 点击登录按钮
            // 点击登录按钮
            WebElement loginButton = driver.findElement(By.xpath("//button[contains(@class, 'el-button') and contains(@class, 'handle-btn')]"));
            loginButton.click();

            // 等待登录完成（根据页面跳转时间调整）
            Thread.sleep(2000);

            log.info("登录成功，返回原页面: " +baseUrl);
            driver.get(baseUrl); // 回到原始爬取页面
            Thread.sleep(1000); // 等待页面加载
        } catch (Exception e) {
            log.error("登录过程中发生错误: ", e);
        }

        try {
            // 查找是否存在关闭按钮，使用 class 定位
            WebElement closeButton = driver.findElement(By.className("el-icon-close"));
            if (closeButton != null) {
                log.info("检测到弹框，正在关闭...");
                closeButton.click(); // 点击关闭按钮
            }
        } catch (Exception e) {
            log.info("没有弹框或关闭弹框失败");
        }

    }

    private static void extractFields(String title, String time, TenderInformation tenderInformation, String websiteName) {

        tenderInformation.setBiddingUnit("--");  // 设置招标单位为“--”
        tenderInformation.setBiddingUnitIndustry("--");  // 设置招标单位行业为“--”
        tenderInformation.setTenderAmount(0.0);  // 设置招标金额为 0.0
        tenderInformation.setBiddingNum("--");
        tenderInformation.setTenderType("--");
        tenderInformation.setStartTime(null);
        tenderInformation.setEndTime(null);
        tenderInformation.setTenderDate(DateUtils.parseDate(time, "yyyy-MM-dd"));
        tenderInformation.setBiddingWinner("--");  // 设置中标单位为“--”
        tenderInformation.setAgency("--");  // 设置代理机构为“--”
        tenderInformation.setTenderTitle(title);
//        tenderInformation.setTenderDesc(title+area+time);
        tenderInformation.setWebsiteName(websiteName);
        tenderInformation.setCrawlTime(new Date());  // 设置爬取时间为当前时间
        tenderInformation.setCreateBy("system");
        tenderInformation.setCreateTime(new Date());
        tenderInformation.setUpdateBy("system");
        tenderInformation.setUpdateTime(new Date());
    }
}

